<?php
use Swoole\Runtime;
use Swoole\Coroutine;
use Swoole\Coroutine\MySQL;
use function Swoole\Coroutine\run;
Runtime::enableCoroutine(true, SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL);

$start_time = microtime(true);

require  __DIR__ .'/../global_default_function.php';

function getAdgroupFeed($header, $database, $user) {
	$doResponse = HttpPost('https://api.baidu.com/json/feed/v1/AdgroupFeedService/getAdgroupFeed', $header);
	if( !$doResponse ) {
		return;
	}
	$bodyArray = json_decode($doResponse, true);
	if( !is_array($bodyArray) ) {
		return;
	}
	if( !isset($bodyArray['header']) ) {
		return;
	}
	if( !isset($bodyArray['header']['desc']) ) {
		return;
	}
	if( $bodyArray['header']['desc'] != 'success' ) {
		return;
	}
	$adgroupIdArray = [];
	$campaignNameArray = $database->query("select campaignId, campaignName from cfg_campaign where `companyId` = '{$user['companyId']}' AND `userType` = 2");
	foreach ($bodyArray['body']['data'] as $value ) {
		array_push($adgroupIdArray, $value['adgroupFeedId']);
		$maxPrice = $value['bid'];
		if(empty($value['bid'])){
			$maxPrice = isset($value['ocpc']['ocpcBid']) ? $value['ocpc']['ocpcBid'] : 0;
		}
		$ftypes       = implode(',', $value['ftypes']);
		$extend1      = serialize($value['ocpc']);
		$extend2      = $value['bidtype'];
		$campaignName = getArrayValue($campaignNameArray, $value['campaignFeedId'], 'campaignId', 'campaignName', null);
		$res = $database->query("select id from cfg_adgroup where `companyId` = '{$user['companyId']}' AND `userType` = 2 AND `userId` = '{$user['userid']}' AND adgroupId = {$value['adgroupFeedId']} LIMIT 1");
		if( isset($res[0]['id']) ) {
			$database->query( "UPDATE cfg_adgroup SET `bazaarId` = '{$user['bazaarId']}', `adgroupName` = '{$value['adgroupFeedName']}', `campaignName` = '{$campaignName}', `status` = '{$value['status']}',
				 `ftypes` = '{$ftypes}', `extend1` = '{$extend1}', `extend2` = '{$extend2}', `maxPrice` = '{$maxPrice}', `datatime` = NOW() WHERE id = {$res[0]['id']} ");
		} else {
				$database->query("INSERT INTO cfg_adgroup ( `companyId`, `userType`, `userId`, `bazaarId`, `adgroupId`,`adgroupName`, `campaignId`, `campaignName`, `status`, `ftypes`, `extend1`, `extend2`, `maxPrice`, `datatime` ) values (
				'{$user['companyId']}', 2, '{$user['userid']}', '{$user['bazaarId']}', '{$value['adgroupFeedId']}', '{$value['adgroupFeedName']}', '{$value['campaignFeedId']}', '{$campaignName}',
				  '{$value['status']}', '{$ftypes}', '{$extend1}', '{$extend2}', '{$maxPrice}', NOW() ) " );
  	}
	}
	switch (count($adgroupIdArray)) {
		case 0:
			$database->query(" DELETE FROM cfg_adgroup WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} " );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `adgroupid` > 0 " );
			break;
		case 1:
			$database->query(" DELETE FROM cfg_adgroup WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} AND `adgroupId` <> {$adgroupIdArray[0]}" );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `adgroupid` > 0 AND `adgroupid` <> {$adgroupIdArray[0]} " );
			break;
		default:
			$notinId = implode(',', $adgroupIdArray);
			$database->query(" DELETE FROM cfg_adgroup WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userId` = {$user['userid']} AND `adgroupId` NOT IN ($notinId) " );
			$database->query(" DELETE FROM cfg_search WHERE `companyId` = {$user['companyId']} AND `userType` = 2 AND `userid` = {$user['userid']} AND `adgroupid` > 0 AND `adgroupid` NOT IN ($notinId) " );
	}
}

function getCampaign($database, $user) {
	$campaignIds = [];
	$campaign = $database->query("select campaignId from cfg_campaign WHERE `companyId` = '{$user['companyId']}' AND `userType` = 2 AND userId = '{$user['userid']}' ");
	if(is_array($campaign)){
		foreach( $campaign as $value) {
			array_push($campaignIds, $value['campaignId']);
		}
	}
	return $campaignIds;
}

run(function() use ($argv) {

	showMessage('读取信息流单元.' );

	$config = getConfig();
	$database = new MySQL();
	$connect = $database->connect($config);
	if( $connect === false) {
		return;
	}

  $userList = $database->query('SELECT `id`, `companyId`, `rebate`, `bazaarId`, `userid`, `username`, `password`, `token` FROM cfg_expand where status = 1 and userType = 2');
	if ($userList === false) {
		showMessage($database->errno . ' - ' . $database->error);
		return;
	}
	$userArray = array_chunk($userList, $config['curlnumber']);
  foreach ($userArray as $arrayList) {
		foreach ($arrayList as $user) {
			go(function() use ($config, $user)  {
				$database = new MySQL;
				$connect = $database->connect($config);
				if( $connect === false) {
					return;
				}
				showMessage($user['username'].'请求信息流单元.' );
				$campaignIds = getCampaign($database, $user);
				if( count($campaignIds) > 0 ) {
					getAdgroupFeed(json_encode([
						'header'=> [ 'username'=> $user['username'], 'password'=> $user['password'], 'token'=> $user['token'] ],
						'body'=> [
							"ids" => $campaignIds,
							"idType" => 1,
							"adgroupFeedFields"=>[
									"adgroupFeedId",
									"campaignFeedId",
									"adgroupFeedName",
									"pause",
									"status",
									"bid",
									"producttypes",
									"ftypes",
									"bidtype",
									"ocpc",
									"atpFeedId",
									"addtime",
							]
						]
					]), $database, $user);
				}
			});
		}
		Swoole\Coroutine::sleep(2);
	}
});

showMessage('执行耗时 ' . round((microtime(true) - $start_time), 3) . ' s');